#### 时间依赖roc ####
library(timeROC)
library(survival)
# 加载必要的包
try({
  setwd('../时间依赖ROC/')
})

try({
  setwd('父级路径')
})

df <- read.table("TCGAriskcore.txt", header = T,sep = "\t", quote = "", check.names = F, row.names = 1)
# 提取生存状态和生存时间
status <- df[[2]]  # 第二列为生存状态
time <- df[[1]]    # 第一列为生存时间

# 提取预测因子
scores <- df[[3]]  # 第三列为模型分数或预测因子

# 使用 Surv 函数构建生存对象
surv_obj <- Surv(time, status)

# 使用 timeROC 函数计算时间依赖的 ROC
roc <- timeROC(T = time, delta = status, marker = scores,
               cause = 1, times = c(365, 730, 1095), iid = TRUE)

# 绘制时间依赖的 ROC 曲线并添加 AUC 值
pdf(file = 'roc.pdf')
plot(roc, time = 365, col = "oneyearcoloar", title = "12个月、24个月和36个月的ROC曲线")
plot(roc, time = 730, add = TRUE, col = "twoyearcoloar")
plot(roc, time = 1095, add = TRUE, col = "threeyearcoloar")
# 添加图例和 AUC 值
legend("bottomright", 
       legend = c(paste("1-year =", round(roc$AUC[1], 3)),
                  paste("2-year =", round(roc$AUC[2], 3)),
                  paste("3-year =", round(roc$AUC[3], 3))),
       col = c("oneyearcoloar", "twoyearcoloar", "threeyearcoloar"), lty = 1, cex = 0.8)

dev.off()

png(file = 'roc.png')
plot(roc, time = 365, col = "oneyearcoloar", title = "12个月、24个月和36个月的ROC曲线")
plot(roc, time = 730, add = TRUE, col = "twoyearcoloar")
plot(roc, time = 1095, add = TRUE, col = "threeyearcoloar")
# 添加图例和 AUC 值
legend("bottomright", 
       legend = c(paste("1-year =", round(roc$AUC[1], 3)),
                  paste("2-year =", round(roc$AUC[2], 3)),
                  paste("3-year =", round(roc$AUC[3], 3))),
       col = c("oneyearcoloar", "twoyearcoloar", "threeyearcoloar"), lty = 1, cex = 0.8)

dev.off()

